package com.example.parkingproject.config;


import com.alibaba.fastjson.JSON;
import com.example.parkingproject.code.ServiceCode;
import com.example.parkingproject.filter.JwtAuthorizationFilter;
import com.example.parkingproject.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * 密码加密
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*添加过滤器 */
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置Spring Security创建Session的策略：STATELESS=从不使用Session，NEVER=不主动创建Session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //处理认证为通过的时候导致的拒绝访问
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                String message = "您还为登录授权，请登录";
                log.warn("{}", message);
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.error_bad_request, message);
                String jsonString = JSON.toJSONString(jsonResult);
                writer.println(jsonString);
                writer.close();
            }
        });



        /*禁用防止伪造的跨域攻击*/
        http.csrf().disable();
        /*允许复杂请求*/
        http.cors();


        /*设置白名单*/
        String[] urls = {
                "/*/*.css",
                "/*/*.js",
                "/user/*",
                "/admin/login",
                "/ParkingSpace/getFreeSpaceList",
                "/car/getCarList",
                "/car/addNewCar",
                "/pay/confirm",
                "https://openapi.alipaydev.com/*",
                "/ParkingSpace/getParkingSpace",
                "/mouthUser/addMouthUser",
                "/car/carIn",
                "/allega/*",
                "/comment/*",
                "/pay/*",

        };

        http.authorizeRequests() // 对请求进行授权
                .mvcMatchers(urls) // 匹配某些请求
                .permitAll() // 直接许可，即不需要认证即可访问
                .anyRequest() // 任意请求
                .authenticated(); // 要求通过认证的

    }
}
